from typing import Optional
from fastapi import HTTPException, status, Depends, Request
from sqlalchemy.orm import Session
from database import get_db, DBUser
from models import UserResponse

active_sessions = {}

def authenticate_user(username: str, password: str, db: Session) -> Optional[DBUser]:
    user = db.query(DBUser).filter(DBUser.username == username).first()
    if not user:
        return None
    if password != user.password:
        return None
    return user

def create_session(username: str) -> str:
    import uuid
    session_id = str(uuid.uuid4())
    active_sessions[session_id] = username
    return session_id

def get_current_user(request: Request, db: Session = Depends(get_db)) -> DBUser:
    authorization = request.headers.get("Authorization")
    if not authorization:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="未提供授权信息",
        )
    
    try:
        scheme, session_id = authorization.split()
        if scheme.lower() != "bearer":
            raise ValueError()
    except ValueError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的授权格式",
        )
    
    username = active_sessions.get(session_id)
    if not username:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="会话已过期或无效",
        )
    
    user = db.query(DBUser).filter(DBUser.username == username).first()
    if not user:
        active_sessions.pop(session_id, None)
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户不存在",
        )
    
    return user

def get_current_admin_user(current_user: DBUser = Depends(get_current_user)) -> DBUser:
    if current_user.role != "admin":
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="权限不足，需要管理员权限"
        )
    return current_user

def logout_session(session_id: str):
    active_sessions.pop(session_id, None)